<template>
  <div class="app-container">
    <div class="detail-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/attraction/' }"
          ><i
            class="el-icon-arrow-left"
            style="font-size: 15px; font-weight: bold; padding-right: 3px"
          ></i
          >{{ attraction_name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item>语音详情</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="save-btn">
        <el-button type="primary" @click="publishVoice" v-if="init_status === 'success'"
          >发布</el-button
        >
      </div>
    </div>
    <div class="detail-create">
      <el-input
        placeholder="请输入新建文件夹名称"
        v-model="dir_name"
        class="input-with-select"
        size="mini"
      >
        <el-button slot="append" @click="createVoice">确定新建</el-button>
      </el-input>
      <div class="create-upload">
        <span>初始化：</span>

        <el-upload
          class="upload-demo"
          action=""
          :show-file-list="false"
          :before-upload="beforeUpload"
        >
          <el-button plain size="mini">
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 -6 24 26">
              <path
                fill="#1677ff"
                class="create-upload-svg"
                d="M11 16V7.85l-2.6 2.6L7 9l5-5l5 5l-1.4 1.45l-2.6-2.6V16zm-7 4v-5h2v3h12v-3h2v5z"
              /></svg
            ><span>上传语音压缩包</span></el-button
          >
        </el-upload>
      </div>
      <div class="edition">
        <span class="edition-span1" v-if="version">语音版本: {{ version }}</span>
      </div>
    </div>

    <Table :data="list" :columns="columns" :loading="listLoading">
      <template v-slot:dir>
        <el-table-column label="名称" width="250" prop="dir" show-overflow-tooltip>
          <template slot-scope="scope"
            ><div class="dir" @click="handleCellClickDetail(scope.row)">
              <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                <path
                  fill="#ffca28"
                  d="M4 20q-.825 0-1.412-.587T2 18V6q0-.825.588-1.412T4 4h6l2 2h8q.825 0 1.413.588T22 8v10q0 .825-.587 1.413T20 20z"
                />
              </svg>
              <!-- <div v-if="editRow !== scope.$index">
                {{ scope.row.name }}
              </div>
              <div v-else>
                <el-input v-model="scope.row.name" size="small" />
              </div> -->
              <p class="dir-name" v-if="editRow !== scope.$index">{{ scope.row.dir }}</p>
              <el-input
                v-model="scope.row.dir"
                size="small"
                v-else
                @blur="saveEdit(scope.$index)"
                placeholder="请输入文件夹名称"
              /></div></template
        ></el-table-column>
      </template>
      <template v-slot:status>
        <el-table-column label="更新状态" width="150" prop="status" align="center">
          <template slot-scope="scope">
            {{
              scope.row.status === 'ing'
                ? '进行中'
                : scope.row.status === 'success'
                ? '成功'
                : '失败'
            }}
          </template>
        </el-table-column>
      </template>

      <template v-slot:action>
        <el-table-column label="操作" minWidth="160" fixed="right">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center; gap: 10px">
              <el-upload
                class="upload-demo"
                action=""
                :show-file-list="false"
                :before-upload="(file) => updateVoiceDir(file, scope.row.id)"
              >
                <el-button plain size="mini"> 上传语音包</el-button>
              </el-upload>
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i class="el-icon-delete table-action" @click="handleDel(scope.row.id)"></i>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </template>
    </Table>
  </div>
</template>

<script>
import {
  getFirmwareList,
  addFirmware,
  publishFirmware,
  delFirmware,
  initAttractionVoice,
  updateVoiceDir
} from '@/api/attraction'
import { cosSign } from '@/api/common'
import { getToken } from '@/utils/auth'
export default {
  name: 'VoiceDetail',
  components: {},
  data() {
    return {
      token: getToken(),
      action: '',
      attraction_id: '', //楼层uuid
      listLoading: false,
      list: [],
      init_status: '',
      version: '',
      dir_name: '',
      attraction_name: '',
      editProp: ['dir'],
      columns: [
        {
          label: '名称',
          slot: 'dir'
        },
        {
          label: '更新状态',
          slot: 'status'
        },
        {
          label: '修改日期',
          prop: 'modified_time',
          width: 180
        },
        {
          label: '操作',
          slot: 'action'
        }
      ],
      editRow: null // 记录正在编辑的行索引
    }
  },
  mounted() {
    const { attraction_id, attraction_name } = this.$route.query

    this.attraction_id = attraction_id
    this.attraction_name = attraction_name

    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      getFirmwareList({ attraction_id: this.attraction_id }).then((res) => {
        const { dirs, init_status, version } = res.data
        this.list = dirs
        this.version = version
        this.init_status = init_status
        this.listLoading = false
      })
    },
    // 确定新建
    createVoice() {
      if (!this.dir_name) return this.$message.error('请输入文件夹名称')
      addFirmware({ dir_name: this.dir_name, attraction_id: this.attraction_id }).then(() => {
        this.fetchData()
        this.dir_name = ''
        this.$message.success('新建成功')
      })
    },

    // 通用的上传语音包方法
    uploadVoicePackage(file, options = {}) {
      const isZip = file.type === 'application/zip' || /\.zip$/.test(file.name)
      if (!isZip) {
        this.$message.error('仅支持上传 ZIP 文件')
        return false // 阻止上传
      }
      console.log('file', file)

      this.listLoading = true
      const formData = new FormData()
      formData.append('file', file)

      return cosSign({ scene: 'voice_init', filename: file.name }).then((response) => {
        console.log('response', response.data)
        this.action = response.data.file_url
        // 手动发起上传请求
        return fetch(response.data.presigned_url, {
          method: 'PUT',
          body: formData,
          headers: {
            token: this.token
          }
        })
          .then((res) => {
            console.log('response', res)
            this.listLoading = false

            // 根据传入的选项决定调用哪个API
            const apiParams = {
              attraction_id: this.attraction_id,
              voice_zip_file: response.data.file_url,
              ...options
            }

            const apiCall = options.dir_id
              ? updateVoiceDir(apiParams)
              : initAttractionVoice(apiParams)

            return apiCall
              .then(() => {
                this.listLoading = false
                this.$message.success('文件上传成功！')
                this.fetchData()
              })
              .catch(() => {
                this.listLoading = false
              })
          })
          .catch((err) => {
            console.log('err', err)
            this.listLoading = false
            console.error('上传失败', err)
            this.$message.error('文件上传失败！')
          })
      })
    },

    beforeUpload(file) {
      this.uploadVoicePackage(file)
      // 阻止 Element UI 默认上传行为
      return false
    },

    updateVoiceDir(file, dir_id) {
      this.uploadVoicePackage(file, { dir_id })
      // 阻止 Element UI 默认上传行为
      return false
    },

    // 提交发布
    publishVoice() {
      publishFirmware({ attraction_id: this.attraction_id }).then(() => {
        this.$message.success('发布成功')
      })
    },
    handleCellClickDetail(row) {
      console.log('row', row)
      this.$router.push({
        path: `/attraction/fileList`,
        query: {
          dir_id: row.id,
          attraction_name: this.attraction_name,
          dir_name: row.dir,
          attraction_id: this.attraction_id
        }
      })
    },

    startEdit(index) {
      this.editRow = index
    },
    saveEdit(index) {
      this.editRow = null
      console.log('index', index)
    },

    /**
     * @description: 删除
     */
    handleDel(id) {
      this.$confirm('确认删除该文件夹吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delFirmware(id).then(() => {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success'
            })
            this.fetchData()
          })
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped lang="less">
.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.detail-create {
  margin-top: 10px;
  margin-bottom: 15px;
}
.input-with-select {
  width: 260px;
}
/deep/ .el-input-group__append,
.el-input-group__prepend {
  background-color: #1677ff !important;
  color: #fff !important;
  &:hover {
    background-color: #66b1ff !important;
  }
}
.detail-create {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.create-upload {
  display: flex;
  align-items: center;
  & > span {
    font-size: 12px;
    color: #666;
  }
  button {
    border-radius: 6px;
    border: 1px solid #1677ff;
    color: #1677ff;
    padding: 0 8px 5px !important;
    &:hover {
      .create-upload-svg {
        fill: #66b1ff;
      }
    }
  }
}
.edition {
  color: #666;
  font-size: 12px;
  .edition-span1 {
    margin-right: 20px;
  }
}
/deep/ .el-breadcrumb__inner.is-link {
  color: #666;
}
.dir {
  display: flex;
  align-items: center;
  cursor: pointer;
  p {
    margin-left: 5px;
  }
}
.dir-input {
  display: none;
}
</style>
